package middleware

import (
	"5title_gin/pkg/redis_ser"
	"5title_gin/pkg/utils/jwts"
	"5title_gin/pkg/utils/res"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strings"
)

func AuthMiddleware(c *gin.Context) {
	// 获取 Authorization 头部
	/*	authHeader := c.GetHeader("Authorization")
		if authHeader == "" || len(authHeader) < 8 || authHeader[:7] != "Bearer " {
			res.FailWithMsg("无效的 Token", c)
			c.Abort()
			return
		}

		// 提取 Token
		token := authHeader[7:]
		zap.S().Warnf("解析 Token: %s", token)*/
	authHeader := c.GetHeader("Authorization")
	parts := strings.Fields(authHeader) // 按空格拆分
	if len(parts) != 2 || parts[0] != "Bearer" {
		res.FailWithMsg("无效的 Token", c)
		c.Abort()
		return
	}

	token := parts[1]
	zap.S().Warnf("解析 Token: %s", token)

	_, err := jwts.CheckToken(token)
	if err != nil {
		res.FailWithMsg("认证失败", c)
		c.Abort()
		return
	}
	if redis_ser.HasLogout(token) {
		res.FailWithMsg("当前登录已注销", c)
		c.Abort()
		return
	}
	c.Next()
	fmt.Println("auth响应")

}

func GetAuth(c *gin.Context) (cl *jwts.MyClaims) {
	cl = new(jwts.MyClaims)
	_claims, ok := c.Get("claims")
	if !ok {
		return
	}
	cl, ok = _claims.(*jwts.MyClaims)
	return
}
